# -*- coding: utf-8 -*-
import os
import sys
from jiqixuexi.cms.models import Article

reload(sys)
sys.setdefaultencoding("utf-8")

import json
import traceback
from django.core import serializers
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
import jiqixuexi.views as action
import jiqixuexi.settings as settings

TARGET_FILE_DIR = settings.BASE_DIR+"/output/"


def index(request):
    return render_to_response('cms/publish/index.html', {})


def generate(request):
    try:
        # copy static files
        # index (1)
        generate_file("index.html", "index.html", action.index_data())
        # index (pages)

        # categories (pages*N)
        # articles (N)
        articles = Article.objects.all()
        for article in articles:
            generate_file("article/"+str(article.id)+".html", "article.html", action.view_article_data(article))
    except:
        traceback.print_exc()

    return JsonResponse({"a": "efs", "b": "bba"})


def generate_file(target, template, params):
    target_file = TARGET_FILE_DIR + target
    content = render_to_string(template, params)
    if not os.path.exists(target_file):
        mkfilePower(target_file)
    with open(target_file, 'w+') as static_file:
        static_file.write(content)
    pass


def mkfilePower(path):
    '''create dirs if the path contain a file create a empty file
    if the dir's file is exist return False else return True

    ex:path = r'c:/temp/gapgers/upload/images/1.png'
    nomatter there have dir temp or not,we will create it and create a empty file 1.png
    '''
    paths = path.split('/')
    temppath = ''
    for index,_spilt in enumerate(paths):
        if index == 0:
            temppath = _spilt
            continue
        temppath = temppath + '/' + _spilt
        if os.path.isdir(temppath):
            pass
        elif index == len(paths)-1:
            if os.path.isfile(temppath):
                return False
            fl = open(temppath, 'w')
            fl.close()
        else:
            os.mkdir(temppath)
    return True

'''
context = {'some_key': 'some_value'}

static_html = '/path/to/static.html'

if not os.path.exists(static_html):
    content = render_to_string('template.html', context)
    with open(static_html, 'w') as static_file:
        static_file.write(content)
'''